package com.losl.framework.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.validation.Valid;

import cn.hutool.core.util.ArrayUtil;
import com.losl.common.annotation.Log;
import com.losl.common.core.domain.model.LoginUser;
import com.losl.common.enums.BusinessType;
import com.losl.common.enums.LogType;
import com.losl.common.util.ServletUtils;
import com.losl.common.util.StringUtils;
import com.losl.framework.web.service.TokenService;
import com.losl.system.service.SysUserService;
import io.swagger.annotations.ApiImplicitParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.losl.common.core.domain.Result;
import com.losl.common.core.domain.BaseController;
import com.losl.common.exception.CustomException;

import com.losl.system.pojo.Posts;
import com.losl.system.service.PostsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;


/**
 * 帖子表 控制器
 * @author maxwell
 * @date 2021-06-04
 */
@RestController
@RequestMapping("/posts")
@Api(value = "帖子表-API", tags = { "帖子表相关接口" })
public class PostsController extends BaseController {
    @Autowired
    private PostsService postsService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysUserService userService;

    /**
     * 帖子表分页列表
     */
    @ApiOperation("分页查询帖子表")
    @ApiImplicitParam(name = "posts", value = "帖子表实体", paramType = "query", dataType = "Posts")
    @GetMapping("/page")
    public Result page(Posts posts) {
        if(StringUtils.isNull(posts)){
            return Result.error("实体类不能为空");
        }
        Page<Posts> page = getPage();
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<Posts>(posts);
        IPage<Posts> pageInfo = postsService.page(page, queryWrapper);
        return Result.success().put("total", pageInfo.getTotal()).put("rows", pageInfo.getRecords());
    }

    /**
     * 查询帖子表列表
     */
    @ApiOperation("查询帖子表列表")
    @ApiImplicitParam(name = "posts", value = "帖子表实体", paramType = "query", dataType = "Posts")
    @GetMapping("/list")
    public Result list(Posts posts) {
        if(StringUtils.isNull(posts)){
            return Result.error("实体类不能为空");
        }
        QueryWrapper<Posts> queryWrapper = new QueryWrapper<Posts>(posts);
        List<Posts> list = postsService.list(queryWrapper);
        return Result.success().put("rows", list);
    }

    /**
     * 根据主键查询帖子表
     */
    @ApiOperation("根据主键查询帖子表")
    @ApiImplicitParam(name = "id", value = "主键", required = true, paramType = "path", dataType = "long")
    @GetMapping("/single/{id}")
    public Result single(@PathVariable("id") Long id) {
        return Result.success().put("obj", postsService.getById(id));
    }

    /**
     * 保存帖子表
     */
    @PreAuthorize("@ps.hasPermission('sys:posts:save')")
    @Log(logtype = LogType.ALL,content ="保存",businessType = BusinessType.INSERT)
    @ApiOperation(value = "创建帖子表", notes = "创建帖子表")
    @ApiImplicitParam(name = "posts", value = "帖子表实体", paramType = "body", dataType = "Posts")
    @PostMapping("/save")
    public Result save(@Valid @RequestBody Posts posts, BindingResult result){
        if (result.hasErrors()) {
           throw new CustomException(result.getFieldError().getDefaultMessage());
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        posts.setAuthorId(loginUser.getUser().getUserId());
        posts.setProfile(loginUser.getUser().getProfile());
        return Result.success().put("flag", postsService.save(posts));
    }

    /**
     * 修改帖子表
     */
    @PreAuthorize("@ps.hasPermission('sys:posts:update')")
    @Log(logtype = LogType.PARAMETER,content ="修改",businessType = BusinessType.UPDATA)
    @ApiOperation(value = "修改帖子表", notes = "修改帖子表")
    @ApiImplicitParam(name = "posts", value = "帖子表实体", paramType = "body", dataType = "Posts")
    @PutMapping("/update")
    public Result update(@RequestBody Posts posts){
        return Result.success().put("flag", postsService.updateById(posts));
    }

    /**
     * 根据主键删除帖子表
     */
    @PreAuthorize("@ps.hasPermission('sys:posts:del')")
    @Log(logtype = LogType.PARAMETER,content ="删除",businessType = BusinessType.DELETE)
    @ApiOperation(value = "根据主键删除帖子表", notes = "根据主键删除帖子表")
    @ApiImplicitParam(name = "id", value = "帖子表主键", required = true, paramType = "path", dataType = "long")
    @DeleteMapping("/del/{id}")
    public Result delete(@PathVariable("id") Long id){
        return Result.success().put("flag", postsService.removeById(id));
    }

    /**
     * 批量删除帖子表
     */
    @PreAuthorize("@ps.hasPermission('sys:posts:del')")
    @Log(logtype = LogType.PARAMETER,content ="批量删除",businessType = BusinessType.DELETE)
    @ApiOperation(value = "批量删除帖子表", notes = "根据主键批量删除帖子表")
    @ApiImplicitParam(name = "ids", value = "主键数组", required = true, paramType = "query", allowMultiple = true, dataType = "Long")
    @DeleteMapping("/dels")
    public Result del(@RequestParam(value = "ids[]") Long[] ids) {
        return Result.success().put("flag", postsService.removeByIds(Arrays.asList(ids)));
    }


    /**
     * 批量更改帖子表的状态
     */
    @PreAuthorize("@ps.hasPermission('sys:posts:status')")
    @ApiOperation(value="批量更改帖子表的状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids",value = "主键数组",required = true, paramType="query",allowMultiple=true,dataType="long"),
            @ApiImplicitParam(name="status",value = "状态数字",required = true, paramType="query",allowMultiple=false,dataType="Integer")
    })
    @PostMapping("/status")
    public Result status(Integer []ids, String status){
        if (StringUtils.isEmpty(status)){
        throw new CustomException("状态错误");
        }else if(ArrayUtil.isEmpty(ids)){
        throw new CustomException("主键数组错误");
        }
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        wrapper.eq("status",status);
        ArrayList<Posts> list = new ArrayList<>();
        for (Integer id : ids) {
        Posts entity = new Posts();
        entity.setStatus(status);
        entity.setPostId(id);
        list.add(entity);
        }
        return Result.success().put("flag",postsService.updateBatchById(list));
    }

    /**
     * 帖子搜索
     */
    @ApiImplicitParam(name = "key",value = "搜索内容",required = true, paramType="query",allowMultiple=false,dataType="string")
    @GetMapping("/search")
    public Result search(String key){
        Page<Posts> page = getPage();
        QueryWrapper<Posts> wrapper = new QueryWrapper<>();
        if (StringUtils.isEmpty(key)){
            wrapper.select("*");
            return Result.success().put("row",postsService.page(page,wrapper));
        }
        wrapper.like("title",key).or()
                .like("author",key);
        return Result.success().put("row",postsService.page(page,wrapper));
    }

    /**
     * 首页
     */
    @ApiOperation("返回首页数据")
    @GetMapping("/index")
    public Result index(){
        System.out.println("done");
        return Result.success().put("data",postsService.index());
    }

}
